/*************************************************************************
	> File Name: list.c
	> Author: Wang Bo
	> Mail: 1276106221@qq.com
	> Created Time: 2020年11月27日 星期五 17时59分43秒
 ************************************************************************/
#include "node.h"
#include "list.h"
#include <stdlib.h>
#include <stdio.h>

List *getNewList() {
    List *l = (List *)malloc(sizeof(List));
    l->length = 0;
    l->head = (Node *)malloc(sizeof(Node));
    l->head->next = NULL;
    return l;
}

Node *getNewListNode(int val) {
    Node *n = (Node *)malloc(sizeof(Node));
    n->data = val;
    n->next = NULL;
    return n;
}

void clearList(List *l) {
    if (l == NULL) return ;
    Node *cur = l->head->next;
    Node *del;
    while (cur) {
        del = cur;
        cur = cur->next;
        free(del);
    }
    free(l->head);
    free(l);
    return;
}

int insertListNode(List *l, int ind, int val) {
    if (l == NULL) return 0;
    if (ind < 0 || ind > l->length) return 0;
    Node *n = getNewListNode(val);
    Node *cur = l->head;
    while (ind--) cur = cur->next;
    n->next = cur->next;
    cur->next = n;
    l->length += 1;
    return 1; 
}

int eraseListNode(List *l, int ind) {
    if (l == NULL) return 0;
    if (ind < 0 || ind >= l->length) return 0;
    Node *cur = l->head;
    while (ind--) cur = cur->next;
    Node *del = cur->next;
    cur->next = del->next;
    free(del);
    l->length -= 1;
    return 1;
}

void outputList(List *l) {
    if (l == NULL) return ;
    Node *cur = l->head->next;
    while (cur) {
        printf("%d->", cur->data);
        cur = cur->next;
    }
    printf("NULL\n");
    return ;
}

void reverseListAt(List *l) {
    if (l == NULL) return ;
    Node *p, *cur = l->head->next;
    l->head->next = NULL;
    while (cur) {
        p = cur;
        cur = cur->next;
        p->next = l->head->next;
        l->head->next = p;
    }
    return ;
}
